package coop.tecso.capacitaciones.threads.counter;

/**
 * Este Runnable modifica el valor del contador incrementandolo o
 * decrementandolo dependiendo de su configuracion inicial
 * 
 * @author fgarcia
 * 
 */
public class CounterModificator implements Runnable {

	private Counter counter;
	private boolean increment;
	private int times;

	/**
	 * Crea el modificador del contador
	 * 
	 * @param counter
	 *            contador a incrementar o decrementar
	 * @param increment
	 *            true si incrementa, false si decrementa el contador
	 * @param times
	 *            cantidad de veces que modifica el contador
	 */
	public CounterModificator(Counter counter, boolean increment, int times) {
		super();
		assert (times > 0);
		this.counter = counter;
		this.increment = increment;
		this.times = times;
	}

	@Override
	public void run() {

		for (int i = 0; i < times; i++) {
			sleep(increment);
			if (increment) {
				counter.increment();
			} else {
				counter.decrement();
			}
		}

	}

	private void sleep(boolean isIncrement) {
		try {
			if (isIncrement) {
				Thread.sleep(3);
			} else {
				Thread.sleep(1);
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
